<template>
  <div id="search_input" style="position: relative;">
    <div class="search_input_row" :class="((searchList.length > 0) || (aiChatRecordList.length > 0 && aiChatRecordShow)) ? 'border_bottom_line':''">
<!--      <div id="icon" :style="{ backgroundImage: 'url(' + getSearchIcon() + ')' }">-->
      <div id="icon">
        <div :class="'search_ai_engine_logo_search'" v-if="search_engine !== 'ai'"/>
        <n-dropdown trigger="hover" :options="search_ai_options" @select="handleAiSelect" v-else>
          <div :class="'search_ai_engine_logo_' + search_ai_engine"></div>
        </n-dropdown>
      </div>
      <div id="input">
        <textarea autofocus v-model="inputValue"
                  v-if="!aiGenerate"
                  @paste="handleImagePaste"
                  @keydown.enter="confirmInput"
                  @compositionstart="handleCompositionStart"
                  @compositionend="handleCompositionEnd"
                  @input="changeInput" ref="aiSearchInput"/>
        <AudioWaveComponent v-else style="margin: auto"/>
      </div>
      <div id="engin">
        <n-dropdown trigger="hover" :options="search_engine_options" @select="handleSelect">
          <div :class="'search_engine_logo_' + search_engine"></div>
        </n-dropdown>
      </div>
    </div>
    
    <div style="margin: 15px;display: grid;grid-template-columns: repeat(6, 1fr);gap: 6px;overflow: hidden" v-if="userChatImages.length > 0">
      <div v-for="(userImage, index) in userChatImages">
        <div class="image_preview" @click="(event) => removeImage(index, event)" :id="'userImagePreview_' + index ">
          <img :src="userImage" style="object-fit: cover;width: 100%;aspect-ratio: 1 / 1;border-radius: 10px;" alt="">
        </div>
      </div>
    </div>

    <div>
      <div style="overflow-y: scroll;max-height: 45vh;" v-if="aiChatRecordShow" @scroll="handleScroll" ref="scrollContainer">
        <div v-for="(record, index) in aiChatRecordList" :key="index" style="flex-grow:1" >
          <div class="ai_chat_record_question_row" v-if="record.question !== ''">
            <div style="font-size: 13px;text-align: right">
              <div style="display:inline-block; text-align: left;background-color: #3188FF;border-radius: 10px;padding: 10px;color: white" v-html="record.question" />
            </div>
            <img src="@/assets/images/system/defaultAvatar.png" alt="" class="ai_chat_user_icon">
          </div>
          <div class="ai_chat_record_answer_row">
            <img src="@/assets/images/system/robot.png" alt="" class="ai_chat_robot_icon">
            <div style="font-size: 13px;">
              <div class="ai_chat_answer_div">
                <div class="ai_chat_think_status" v-if="record.answerLoading">
                  <img src="@/assets/images/system/loading.gif" alt="" class="ai_chat_loading_icon" v-if="record.searchLoading">
                  <span>{{(record.searchLoading ? ((record.searchContentFlag) ? ('正在阅读:' + record.readNetData) : '联网搜索中...') : (record.searchContentFlag ? '回答中' : (record.answer === '' ? '思考中' : '回答中')))}}</span>
                </div>
                <div style="clear: both" v-html="record.answer"/>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div style="overflow-y: scroll;max-height: 45vh;">
        <div v-for="(item, index) in searchList" :key="index" >
          <div class="search_item_row"
               @click="selectConfirm(index)"
               @mouseover="item.hover = true"
               @mouseleave="item.hover = false">
            <img :src="getSearchTypeIcon(item.type, item.hover)" alt="" class="search_item_icon" :style="getSearchTypeIconClass(item.type, item.hover)">
            <div id="search_item_content">
              <span class="search_item_content" v-html="item.name" />
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

</template>

<script>
import AudioWaveComponent from '../components/AudioWaveComponent.vue'
import notification from '../../utils/notification'

export default {
  components: {AudioWaveComponent},
  props: ['searchList', 'aiChatRecordList', 'aiChatRecordShow'],
  data() {
    return {
      inputValue: '',
      aiGenerate: false,
      search_engine: "baidu",
      search_ai_engine: "kimi",
      search_engine_options: [
        {label: "智能", key: "ai", icon: () => h("img", {src: new URL("@/assets/images/search/ai.svg", import.meta.url).href, style: {width: "20px", height: "20px"}})},
        {label: "百度", key: "baidu", icon: () => h("img", {src: new URL("@/assets/images/search/baidu.svg", import.meta.url).href, style: {width: "18px", height: "18px"}})},
        {label: "必应", key: "biying", icon: () => h("img", {src: new URL("@/assets/images/search/biying.svg", import.meta.url).href, style: {width: "20px", height: "20px"}})},
        {label: "谷歌", key: "google", icon: () => h("img", {src: new URL("@/assets/images/search/google.svg", import.meta.url).href, style: {width: "18px", height: "18px"}})}
      ],
      search_ai_options: [
        {label: "KIMI", key: "kimi", icon: () => h("img", {src: new URL("@/assets/images/search/ai-kimi.png", import.meta.url).href, style: {width: "20px"}})},
        {label: "DeepSeek-R1", key: "deepseek", icon: () => h("img", {src: new URL("@/assets/images/search/ai-deepseek.png", import.meta.url).href, style: {width: "20px"}})},
        {label: "GPT-4o", key: "chatgpt", icon: () => h("img", {src: new URL("@/assets/images/search/ai-chatgpt.png", import.meta.url).href, style: {width: "20px"}})}
      ],
      isComposing: false,
      userInterfered: false,
      scrollTimer: null,
      userChatImages: []
    }
  },
  computed: {
    getSearchTypeIconClass() {
      return (type, hover) => {
        if (!hover) return {};

        const colorMap = {
          'bookmark': {
            border: '1.5px solid #BAE6FC',
            boxShadow: '0 0 4px 2px #BAE6FC'
          },
          'favorite': {
            border: '1.5px solid #E8D1FE',
            boxShadow: '0 0 4px 2px #E8D1FE'
          },
          'search': {
            border: '1.5px solid #2196F3',
            boxShadow: '0 0 4px 2px rgba(33, 150, 243, 0.3)'
          }
        };

        return colorMap[type] || {};
      };
    },
  },
  methods: {

    clearInput() {
      this.inputValue = '';
      this.userInterfered = false;
    },
    aiGenerateStart() {
      this.search_engine = 'ai_generate';
      this.aiGenerate = true;
    },
    aiGenerateOver() {
      this.search_engine = 'ai';
      this.aiGenerate = false;
      this.$nextTick(() => {
        this.$refs.aiSearchInput.focus();
      });
    },
    handleScroll() {
      const container = this.$refs.scrollContainer;
      // 检查用户是否接近底部
      const isAtBottom =
          container.scrollHeight - container.scrollTop - container.clientHeight < 10;

      if (isAtBottom) {
        // 用户已回到底部，取消干涉状态
        this.userInterfered = false;
      } else {
        // 用户干涉滚动
        this.userInterfered = true;
      }
    },
    scrollToBottom() {
      if (this.search_engine === 'ai_generate' && !this.userInterfered) {
        const container = this.$refs.scrollContainer;
        container.scrollTop = container.scrollHeight;
      }
    },
    // 处理搜索引擎选择
    handleSelect(key) {
      this.search_engine = key;
      // 设置缓存
      localStorage.setItem("search_engine", this.search_engine);
      this.$emit('change:engine', this.search_engine)
    },
    handleAiSelect(key) {
      this.search_ai_engine = key;
      // 设置缓存
      localStorage.setItem("search_ai_engine", this.search_ai_engine);
      this.$emit('change:ai-engine', this.search_ai_engine)
    },
    getSearchIcon() {
      return require('@/assets/images/search/ai-kimi.png');
    },
    getSearchTypeIcon(type, hover) {
      let suffix = hover ? "_hover" : "";
      if (type === 'bookmark') {
        return require("@/assets/images/recommend/bookmark" + suffix + ".png");
      } else if (type === 'favorite') {
        return require("@/assets/images/recommend/collection" + suffix + ".png");
      } else {
        return require("@/assets/images/recommend/web_search" + suffix + ".png");
      }
    },
    handleImagePaste(event) {
      if (this.userChatImages.length >= 5) {
        notification.error('最多支持5个附件')
        return;
      }
      const items = event.clipboardData.items;
      let file = null;

      // 遍历粘贴内容，查找图片类型
      for (let i = 0; i < items.length; i++) {
        if (items[i].type.indexOf("image") !== -1) {
          file = items[i].getAsFile();
          break;
        }
      }

      if (!file) {
      //   alert("粘贴内容非图片");
        return;
      }

      // 将图片转换为 URL 并进行预览
      this.file = file;
      this.userChatImages.push(URL.createObjectURL(file));
    },
    removeImage(index, event) {
      const container = event.currentTarget;
      const rect = container.getBoundingClientRect(); // 获取容器的边界信息
      const x = event.clientX - rect.left; // 点击位置相对于容器的X坐标
      const y = event.clientY - rect.top; // 点击位置相对于容器的Y坐标
      const closeIconSize = 16; // 假设叉号的大小为30px × 30px
      const closeIconX = rect.width - closeIconSize; // 叉号的X坐标（右上角，留出5px边距）
      const closeIconY = 16;

      // 判断点击位置是否在叉号区域内
      if (x >= closeIconX && y <= closeIconY) {
        this.userChatImages.splice(index, 1);
      }
    },
    confirmInput(event) {
      if (this.isComposing === true) return;
      let data = {
        "value": event.target.value,
        "engine": this.search_engine,
        "altKey": event.altKey
      }
      this.$emit('confirm:input', data)
      event.preventDefault();
    },
    handleCompositionStart() {
      this.isComposing = true;
    },
    handleCompositionEnd(event) {
      this.isComposing = false;
      this.changeInput(event);
    },
    changeInput(event) {
      if (this.isComposing === true) {
        return
      }
      let data = {
        "value": event.target.value,
        "engine": this.search_engine
      }
      this.$emit('change:input', data)
    },
    selectConfirm(index) {
      let data = {
        "index": index,
        "value": this.searchList[index]
      }
      this.$emit('confirm:select', data)
    }
  },
  mounted() {
    // 初始化数据
    this.search_engine = localStorage.getItem("search_engine") || 'baidu';
    // 设置定时器
    this.scrollTimer = setInterval(this.scrollToBottom, 200);
  },

  beforeDestroy() {
    clearInterval(this.scrollTimer);
  }
}
</script>
<style scoped>
::selection {
  color: white;
  background-color: #B042BF;
}
</style>
<style>
#wrapper {
  position: relative; /* 让子元素相对 #wrapper 定位 */
  height: auto; /* 根据内容动态调整高度 */
}
#wrapper::after {
  content: '';
  display: block;
  height: 100px; /* 子元素的高度，这里是最大高度的动态调整值 */
}
body {
  --input_height: 48px;
  --search_logo_wight: 50px;
  --search_engine_wight: 50px;
  font-size: 20px;
}
#search_input {
  z-index: 999;
  width: 95vw;
  min-height: var(--input_height);
  max-width: 800px;
  border-radius: 15px;
  outline: none;
  overflow: hidden;
  backdrop-filter: blur(30px);
  background: rgba(255, 255, 255, 0.4);
  box-shadow: inset 0 15px 30px 0 rgba(255, 255, 255, 0.2), inset 0 0 15px 0 rgba(255, 255, 255, 0.2), inset 0 1px 1px 0 rgba(255, 255, 255, 0.5), inset 0 0 2px 0 rgba(255, 255, 255, 0.7);
  //background: rgba(255, 255, 255, 1);
  //box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  transition: box-shadow 0.3s ease, background 0.3s ease;
}
#search_input:hover {
  background: rgba(255, 255, 255, 0.5);
  box-shadow:
      inset 0 15px 30px 0 rgba(255, 255, 255, 0.2),
      inset 0 0 15px 0 rgba(255, 255, 255, 0.2),
      inset 0 1px 1px 0 rgba(255, 255, 255, 0.5),
      inset 0 0 2px 0 rgba(255, 255, 255, 0.7), 0 0 5px 0 rgba(255, 255, 255, 0.5)
}
.border_bottom_line {
   border-bottom: 1px dashed lightgray;
}
.search_input_row {
  display: grid;
  grid-template-columns: var(--search_logo_wight) auto var(--search_engine_wight);
}

.search_item_row {
  display: grid;
  grid-template-columns: var(--search_logo_wight) auto var(--search_engine_wight);
}
.search_item_row:hover {
  background-color: white;
}

#icon {
  //margin: auto;
  //width: 100%;
  //height: var(--input_height);
  ////background-image: url("https://gips2.baidu.com/it/u=2946987974,984266768&fm=3028&app=3028&f=PNG&fmt=auto&q=75&size=f48_48");
  //background-repeat: no-repeat;
  //background-position: center;
  //background-size: 20px;

  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  width: 100%;
  cursor: pointer;
}

#input {
  height: var(--input_height);
  display: flex;
  align-items: center;
}

#input > textarea {
  font-size: 16px;
  line-height: 20px;
  height: 20px;
  outline: none;
  border: none;
  width: 100%;
  white-space: nowrap;
  resize: none;
  overflow: hidden;
  padding-top: 0;
  padding-bottom: 0;
  background: transparent;
}

#engin {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  width: 100%;
  cursor: pointer;
}

#engin > img {
  width: 25px;
}

#search_item_content {
  height: 38px;
  display: flex;
  align-items: center;
  overflow: hidden;
  user-select: none;
}

#search_item_content > span {
  font-size: 14px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.search_item_icon {
  width: 15px;
  height: 15px;
  //margin: auto 8px auto auto;
  margin: auto;
  padding: 2px;
  border-radius: 7px;
  border: 1.5px solid #F3F3F4;
  background-color: white;
}
.ai_chat_user_icon {
  width: 30px;
  height: auto;
  margin: 5px auto;
  //padding: 2px;
  border-radius: 20px;
}
.ai_chat_robot_icon {
  width: 35px;
  height: auto;
  margin: 5px auto;
  //padding: 2px;
  border-radius: 20px;
}
.ai_chat_answer_div {
  display:inline-block;
  text-align: left;
  background-color: white;
  border-radius: 10px;
  padding: 10px;
  max-width: 580px;
}
.ai_chat_think_status {
  margin: 5px 0;
  color: #1C83F4;
  font-weight: bold;
  background-color: #f6f6f6;
  border-radius: 20px;
  padding: 3px 6px;
  display: flex;
  float: left;
  max-width: 400px;
  overflow: hidden;
  white-space: nowrap;
}
.ai_chat_loading_icon {
  height: 20px;
  margin: 0 auto;
  padding: 2px;
}
.ai_chat_record_question_row {
  margin: 20px 0 20px 50px;
  display: grid;
  grid-template-columns: auto var(--search_logo_wight);
}
.ai_chat_record_answer_row {
  margin: 20px 50px 20px 0;
  display: grid;
  grid-template-columns: var(--search_logo_wight) auto;
}
.ai_chat_record_answer_row p {
  margin: 0 !important;
}
.image_preview {
  width: 100%;
  position: relative;
}
.image_preview::before {
  top: 0; right: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  content: "×";
  position: absolute;
  width: 16px; /* 圆的直径 */
  height: 16px; /* 圆的直径 */
  border-radius: 50%; /* 让元素变成圆形 */
  background-color: #D81E07;
  color: white;
  font-size: 16px;
  cursor: pointer;
}
pre {
  background-color: #282C34;
  color: white;
  font-size: 13px;
  padding: 40px 10px 10px 15px;
  border-radius: 10px;
  overflow: auto; /* 当内容超出时显示滚动条 */
  max-width: 100%; /* 可以设置为你想要的最大宽度，比如 600px */
  box-shadow: 0 0 10px 1px #282C34;
  position: relative;
}

pre:after {
  position: absolute;
  width: 100%;
  height: 1px;
  top: 30px;
  left: 0;
  background-color: darkgrey;
}

pre::before {
  content: ''; /* 必须的，为伪元素创建内容 */
  position: absolute; /* 绝对定位 */
  width: 10px; /* 圆的直径 */
  height: 10px; /* 圆的直径 */
  border-radius: 50%; /* 让元素变成圆形 */
  top: 10px; /* 圆心距离 pre 元素顶部的距离 */
  left: 10px; /* 圆心距离 pre 元素左侧的距离 */
  background-color: #FE5F57; /* 圆的颜色 */
  box-shadow: 15px 0 #FEBC2E, 30px 0 #29C941; /* 画出第二和第三个圆 */
}
textarea:disabled {
  background-color: white;
}
code {
  overflow: visible; /* 允许内容溢出 */
}
table {
  border-collapse: collapse;
  margin: 5px 0;
}
th {
  border: 2px solid white;
  background-color: rgba(107, 66, 218, 0.8);
  backdrop-filter: blur(10px);
  color: white;
  padding: 0 5px;
}
td {
  border: 2px solid white;
  background-color: #f3f3f3;
  padding: 0 5px;
}
.search_ai_engine_logo_chatgpt {
  margin: auto;
  width: 100%;
  height: var(--input_height);
  background-repeat: no-repeat;
  background-position: center;
  background-size: 20px;
  background-image: url("@/assets/images/search/ai-chatgpt.png") !important;
}
.search_ai_engine_logo_deepseek {
  margin: auto;
  width: 100%;
  height: var(--input_height);
  background-repeat: no-repeat;
  background-position: center;
  background-size: 20px;
  background-image: url("@/assets/images/search/ai-deepseek.png") !important;
}
.search_ai_engine_logo_kimi {
  margin: auto;
  width: 100%;
  height: var(--input_height);
  background-repeat: no-repeat;
  background-position: center;
  background-size: 24px;
  background-image: url("@/assets/images/search/ai-kimi.png") !important;
}
.search_ai_engine_logo_search {
  margin: auto;
  width: 100%;
  height: var(--input_height);
  background-repeat: no-repeat;
  background-position: center;
  background-size: 22px;
  background-image: url("@/assets/images/search.svg") !important;
}
.search_engine_logo_ai_generate {
  margin: auto;
  width: 100%;
  height: var(--input_height);
  background-repeat: no-repeat;
  background-position: center;
  background-size: auto 20px;
  background-image: url("@/assets/images/search/ai.svg") !important;
}
.search_engine_logo_baidu {
  margin: auto;
  width: 100%;
  height: var(--input_height);
  background-repeat: no-repeat;
  background-position: center;
  background-size: 20px 20px;
  background-image: url("@/assets/images/search/baidu.svg") !important;
}

.search_engine_logo_biying {
  margin: auto;
  width: 100%;
  height: var(--input_height);
  background-repeat: no-repeat;
  background-position: center;
  background-size: 25px 25px;
  background-image: url("@/assets/images/search/biying.svg") !important;
}

.search_engine_logo_google {
  margin: auto;
  width: 100%;
  height: var(--input_height);
  background-repeat: no-repeat;
  background-position: center;
  background-size: 25px 25px;
  background-image: url("@/assets/images/search/google.svg") !important;
}

.search_engine_logo_ai {
  margin: auto;
  width: 100%;
  height: var(--input_height);
  background-repeat: no-repeat;
  background-position: center;
  background-size: 25px 25px;
  background-image: url("@/assets/images/search/ai.svg") !important;
}

</style>